﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PhoneServiceTest
{
    public class Message
    {
        public int command_length
        {
            get;
            set;
        }

        public string func_no
        {
            get;
            set;
        }

        public string seq_no;

        public MessageBody Body
        {
            get;
            set;
        }
        /// <summary>
        /// 是否话机向服务器
        /// </summary>
        public bool IsRequest
        {
            get;
            set;
        }


        public byte[] GetBytes()
        {
            //byte[] bytes = new byte[command_length];
            var array_func_no = Encoding.Default.GetBytes(func_no);
            var array_seq_no = Encoding.Default.GetBytes(seq_no);
            var array_body = Body.GetBytes();
            command_length = 10 + array_body.Length;
            var array_len = Encoding.Default.GetBytes(command_length.ToString().PadLeft(4, '0'));

            return array_len
                .Concat(array_func_no)
                .Concat(array_seq_no)
                .Concat(array_body)
                .ToArray();

        }

        public void FromBytes(byte[] bytes)
        {
            var length = Encoding.Default.GetString(bytes, 0, 4);
            var func = Encoding.Default.GetString(bytes, 4, 2);
            var seq_no = Encoding.Default.GetString(bytes, 6, 4);
            this.command_length = Convert.ToInt32(length);
            this.func_no = func;
            this.seq_no = seq_no;
            Type bodyType = ProgramCache.MESSAGEBODY_TYPES_CACHE[func_no + (Convert.ToInt32(IsRequest)).ToString()];//区分收到和发送
            if (bodyType != null)
            {
                this.Body = Activator.CreateInstance(bodyType) as MessageBody;
                this.Body.FromBytes(bytes);
            }

        }


    }
}
